import { Table, Space, Modal, Button, Form, Input } from 'antd';
import { useEffect, useState } from "react";
import { adminAPI } from "../../apis/user";
import UserForm from "./common/user-form";
import modStl from './user-list.mod.less';
import { PlusOutlined, ReloadOutlined } from "@ant-design/icons";
import StatusSwitch from "./common/status-switch";
import TableResizeBtn from "../../component/table-resize-btn";
import { SizeType } from "antd/es/config-provider/SizeContext";
import TableColumnSetting from "../../component/table-column-setting";
import TableSelectionAlert from "../../component/table-selection-alert";
import { fmtDateTime } from "../../utils";
import { sortKeys } from "../../utils/constant";
import { Tooltip } from 'antd'

interface UserRecordType {
  title: string
  dataIndex?: string,
  key: string,
  render?: any
  sorter?: any
  sortDirections?: any
  defaultSortOrder?: any
  filters?: any[]
  width?: string | number
}

type OrderType = "ASC" | "DESC"

const UserListPage = () => {
  const actions = {
    "add": 'add',
    "del": 'del',
    "edit": "edit"
  }

  const columns: UserRecordType[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60
    },
    {
      title: '昵称',
      dataIndex: 'username',
      key: 'username',
      width: '15%'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      width: '20%'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_: string, record: any) => {
        return <StatusSwitch record={ record }/>
      },
      filters: [
        {text: '可用', value: '1'},
        {text: '禁用', value: '0'},
      ],
      width: '20%'
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      defaultSortOrder: 'ascend',
      width: '25%',
      render: (t: string) => {
        return <span>{ fmtDateTime(t) }</span>
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (text: string, record: any) => (
        <Space size="small">
          <Button type="link" size={ "small" } onClick={ () => btnHandler(actions.edit, record) }>
            编辑
          </Button>
          <Button type="link" size={ "small" } onClick={ () => showDelConfirm(record) }>删除</Button>
        </Space>
      )
    }
  ];

  const [list, setList] = useState([]);
  const [pager, setPager] = useState({
    pageSize: 10,
    pageIndex: 1,
    total: 0
  });
  const [loading, setLoading] = useState(false);
  const [isEditVisible, setIsEditVisible] = useState(false);
  const [curAction, setCurAction] = useState('');
  const [isUserFormLoading, setIsUserFormLoading] = useState(false);
  const [searchKey, setSearchKey] = useState('');
  const [userItem, setUserItem] = useState(null);
  const [tableSize, setTableSize] = useState<SizeType>("middle");
  const [selectColumn, setSelectColumn] = useState<string[]>(columns.map(it => it.key));
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [sortInfo, setSortInfo] = useState<any>({
    order: '',
    field: ''
  });
  const [filters, setFilters] = useState<any>([]);

  useEffect(getTableData, [
    pager.pageIndex,
    pager.pageSize,
    searchKey,
    sortInfo,
    filters
  ]);

  const onSelectChange = (selectedRowKeys: any[]) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  function onChange(pagination: any, filters: any, sorter: any, extra: any) {
    setFilters(filters);
    if (sorter.order) {
      setSortInfo({
        order: sorter.order,
        field: sorter.field
      })
    } else {
      setSortInfo({
        order: '',
        field: ''
      })
    }
  }

  /**
   * @desc 获取用户列表
   * @author Gaollard
   */
  function getTableData() {
    setLoading(true);
    const params = {
      pageIndex: pager.pageIndex,
      pageSize: pager.pageSize,
    };

    if (sortInfo.order && sortInfo.field) {
      Object.assign(params, {
        sortField: sortInfo.field,
        sortOrder: (sortKeys as any)[sortInfo.order]
      })
    }

    if (searchKey) {
      Object.assign(params, {searchKey})
    }

    if (filters.status) {
      Object.assign(params, {status: filters.status})
    }

    adminAPI.adminList(params)
      .then((res: any) => {
        if (res && res.success) {
          // @ts-ignore
          setList([...res.data.list])
          setPager({
            ...pager,
            total: res.data.total
          });
        }
      })
      .finally(() => {
        setLoading(false)
      })
  }

  const handleOk = () => {
    form.submit();
  };

  const handleCancel = () => {
    if (curAction === actions.edit) {
      setUserItem(null);
    }
    setIsEditVisible(false);
  };

  function btnHandler(action: string, row?: any) {
    setCurAction(action);
    switch (action) {
      case actions.add:
        setIsEditVisible(true);
        break;
      case actions.edit:
        setIsEditVisible(true);
        setUserItem(row);
        break;
    }
  }

  /**
   * @desc 删除用户
   * @author Gaollard
   * @param record
   */
  function showDelConfirm(record: any) {
    Modal.confirm({
      title: '确认删除用户吗？',
      content: `用户 ${ record.username } 等被删除后将无法恢复`,
      onOk() {
        return adminAPI.adminDelete(record.id).then((res: any) => {
          if (res && res.success) {
            getTableData();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const [form] = Form.useForm();  // 添加
  const [sForm] = Form.useForm(); // 搜索

  return (
    <div>
      <div className={ modStl['table-toolbar'] }>
        <Form form={ sForm } onFinish={ (values) => setSearchKey(values.searchKey) } name="sForm" layout={ "inline" }>
          <Form.Item name="searchKey">
            <Input placeholder={ "用户帐号" } allowClear={ true } value={ searchKey }/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
        <Space size={ "large" }>
          <Button type="primary" icon={ <PlusOutlined/> } onClick={ () => btnHandler(actions.add) }>
            新建
          </Button>
          <Space size={ "middle" }>
            <a className="ui-hover-text" onClick={ e => e.preventDefault() }>
              <ReloadOutlined onClick={ getTableData }/>
            </a>
            <TableResizeBtn onChange={ setTableSize } defaultKey={ tableSize }/>
            <TableColumnSetting selectColumns={ selectColumn } columns={ columns } onChange={ setSelectColumn }/>
          </Space>
        </Space>
      </div>

      <TableSelectionAlert selectedRowKeys={ selectedRowKeys } onClickCancel={ () => setSelectedRowKeys([]) }/>

      <Table
        onChange={ onChange }
        rowKey={ "id" }
        bordered
        rowSelection={ {
          type: "checkbox",
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        } }
        columns={ columns.filter(it => selectColumn.includes(it.key)) }
        loading={ loading }
        size={ tableSize }
        dataSource={ list }
        pagination={ {
          showQuickJumper: false,
          showTotal: () => `共 ${ pager.total } 条`,
          pageSize: pager.pageSize,
          total: pager.total,
          current: pager.pageIndex,
          onChange: (v) => setPager({...pager, pageIndex: v}),
        } }
      />
      <Modal
        title={ curAction === actions.add ? "添加用户" : "编辑用户" }
        width={ 500 }
        visible={ isEditVisible }
        onOk={ handleOk }
        onCancel={ handleCancel }
        okButtonProps={ {loading: isUserFormLoading} }
      >
        <UserForm
          form={ form }
          setSubmitLoading={ setIsUserFormLoading }
          onSubmitSuccess={ () => {
            setUserItem(null);
            setIsEditVisible(false);
            pager.pageIndex !== 1 ? setPager({
              ...pager,
              pageIndex: 1
            }) : getTableData()
          } }
          isEdit={ Boolean(userItem) }
          userItem={ userItem }
        />
      </Modal>
    </div>
  )
}

export default UserListPage